"use client"

import { useEffect, useState } from "react"
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Platform, Image, Dimensions } from "react-native"
import { useRouter } from "expo-router"
import { ArrowLeft, BookOpen, Star, ChevronRight } from "lucide-react-native"
import { theme } from "../../constants/theme"
import AsyncStorage from "@react-native-async-storage/async-storage"
import { StatusBar } from "expo-status-bar"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"

const { width } = Dimensions.get("window")
const CARD_WIDTH = width - theme.spacing.lg * 2

// 定义计划书籍类型
interface PlanBook {
    id: string
    title: string
    subtitle: string
    coverColor: string
    totalWords: number
    learnedWords: number
    isActive?: boolean // 是否是当前选中的书本
}

export default function PlanListScreen() {
    const router = useRouter()
    const [planBooks, setPlanBooks] = useState<PlanBook[]>([])
    const [loading, setLoading] = useState(true)
    const [activeBookId, setActiveBookId] = useState<string | null>(null)

    // 加载有计划的书籍
    useEffect(() => {
        const loadPlanBooks = async () => {
            try {
                // 获取当前活跃的书本ID
                const activeBookData = await AsyncStorage.getItem("selectedPlanBook")
                let activeId = null
                if (activeBookData) {
                    const activeBook = JSON.parse(activeBookData)
                    activeId = activeBook.id
                    setActiveBookId(activeId)
                }

                // 模拟从AsyncStorage获取所有书籍计划
                const mockBooks = [
                    {
                        id: "book1",
                        title: "人教版英语",
                        subtitle: "七年级上册",
                        coverColor: "#5B8EF4",
                        totalWords: 448,
                        learnedWords: 3,
                        isActive: activeId === "book1",
                    },
                    {
                        id: "book2",
                        title: "牛津英语",
                        subtitle: "八年级上册",
                        coverColor: "#FF9500",
                        totalWords: 350,
                        learnedWords: 120,
                        isActive: activeId === "book2",
                    },
                    {
                        id: "book3",
                        title: "新概念英语",
                        subtitle: "第一册",
                        coverColor: "#7C4DFF",
                        totalWords: 200,
                        learnedWords: 50,
                        isActive: activeId === "book3",
                    },
                ]

                setPlanBooks(mockBooks)
            } catch (error) {
                console.error("加载计划书籍失败", error)
            } finally {
                setLoading(false)
            }
        }

        loadPlanBooks()
    }, [])

    // 处理选择书本并返回
    const handleSelectBook = (bookId: string) => {
        // 先保存选中的书籍，然后返回上一页
        const selectedBook = planBooks.find((book) => book.id === bookId)
        if (selectedBook) {
            AsyncStorage.setItem(
                "selectedPlanBook",
                JSON.stringify({
                    id: selectedBook.id,
                    title: selectedBook.title,
                    subtitle: selectedBook.subtitle,
                    total: selectedBook.totalWords,
                }),
            ).then(() => {
                router.back() // 返回上一页而不是导航到新页面
            })
        }
    }

    // 处理添加计划按钮点击
    const handleAddPlan = () => {
        router.push({
            pathname: "/books-screen",
            params: { source: "plan_add" },
        })
    }

    // 渲染书籍卡片
    const renderBookCard = ({ item }: { item: PlanBook }) => {
        const progressPercent = Math.round((item.learnedWords / item.totalWords) * 100) || 0

        return (
            <TouchableOpacity style={styles.bookCard} onPress={() => handleSelectBook(item.id)} activeOpacity={0.9}>
                <LinearGradient colors={["#FFFFFF", "#F8F9FA"]} style={styles.cardGradient}>
                    {/* 书籍封面 */}
                    <View style={styles.bookCoverContainer}>
                        <LinearGradient
                            colors={[item.coverColor, shadeColor(item.coverColor, -20)]}
                            start={{ x: 0, y: 0 }}
                            end={{ x: 1, y: 1 }}
                            style={styles.bookCover}
                        >
                            <View style={styles.bookIconContainer}>
                                <BookOpen size={24} color="#FFFFFF" />
                            </View>
                            <Text style={styles.coverTitle}>{item.title.split(" ")[0]}</Text>
                            <Text style={styles.coverSubtitle}>{item.subtitle}</Text>

                            {/* 装饰元素 */}
                            <Image
                                source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341139.png" }}
                                style={styles.decorationImage}
                            />
                        </LinearGradient>
                    </View>

                    {/* 书籍信息 */}
                    <View style={styles.bookInfo}>
                        <View style={styles.bookHeader}>
                            <View style={styles.titleContainer}>
                                <Text style={styles.bookTitle}>{item.title}</Text>
                                <Text style={styles.bookSubtitle}>{item.subtitle}</Text>
                            </View>

                            {/* 只有当前选中的书本显示"正在学习"状态 */}
                            {item.isActive && (
                                <View style={styles.statusBadge}>
                                    <Star size={14} color="#FFFFFF" />
                                    <Text style={styles.statusText}>正在学习</Text>
                                </View>
                            )}
                        </View>

                        {/* 进度信息 */}
                        <View style={styles.progressSection}>
                            <View style={styles.progressInfo}>
                                <View style={styles.progressItem}>
                                    <Text style={styles.progressLabel}>已学单词</Text>
                                    <Text style={styles.progressValue}>{item.learnedWords}</Text>
                                </View>

                                <View style={styles.progressDivider} />

                                <View style={styles.progressItem}>
                                    <Text style={styles.progressLabel}>总词数</Text>
                                    <Text style={styles.progressValue}>{item.totalWords}</Text>
                                </View>

                                <View style={styles.progressDivider} />

                                <View style={styles.progressItem}>
                                    <Text style={styles.progressLabel}>完成度</Text>
                                    <Text style={[styles.progressValue, { color: item.coverColor }]}>{progressPercent}%</Text>
                                </View>
                            </View>

                            {/* 进度条 */}
                            <View style={styles.progressBarContainer}>
                                <View style={styles.progressBar}>
                                    <View
                                        style={[
                                            styles.progressFill,
                                            {
                                                width: `${progressPercent}%`,
                                                backgroundColor: item.coverColor,
                                            },
                                        ]}
                                    />
                                </View>
                            </View>
                        </View>

                        {/* 开始学习按钮 */}
                        <TouchableOpacity
                            style={[styles.startButton, { backgroundColor: item.coverColor }]}
                            onPress={() => handleSelectBook(item.id)}
                            activeOpacity={0.7}
                        >
                            <Text style={styles.startButtonText}>开始学习此计划</Text>
                            <ChevronRight size={16} color="#FFFFFF" />
                        </TouchableOpacity>
                    </View>
                </LinearGradient>
            </TouchableOpacity>
        )
    }

    // 辅助函数：调整颜色深浅
    const shadeColor = (color: string, percent: number) => {
        let R = Number.parseInt(color.substring(1, 3), 16)
        let G = Number.parseInt(color.substring(3, 5), 16)
        let B = Number.parseInt(color.substring(5, 7), 16)

        R = Math.floor((R * (100 + percent)) / 100)
        G = Math.floor((G * (100 + percent)) / 100)
        B = Math.floor((B * (100 + percent)) / 100)

        R = R < 255 ? R : 255
        G = G < 255 ? G : 255
        B = B < 255 ? B : 255

        const RR = R.toString(16).length === 1 ? "0" + R.toString(16) : R.toString(16)
        const GG = G.toString(16).length === 1 ? "0" + G.toString(16) : G.toString(16)
        const BB = B.toString(16).length === 1 ? "0" + B.toString(16) : B.toString(16)

        return "#" + RR + GG + BB
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <StatusBar style="dark" />

            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 头部导航 */}
                <View style={styles.header}>
                    <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
                        <ArrowLeft size={22} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>我的学习计划</Text>
                    <View style={styles.placeholderView} />
                </View>

                {/* 页面说明 */}
                <View style={styles.pageDescription}>
                    <Image
                        source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341025.png" }}
                        style={styles.descriptionIcon}
                    />
                    <Text style={styles.descriptionText}>选择一个学习计划开始今天的学习之旅吧！</Text>
                </View>

                {/* 内容区域 */}
                <View style={styles.content}>
                    {loading ? (
                        <View style={styles.loadingContainer}>
                            <Image
                                source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341025.png" }}
                                style={styles.loadingImage}
                            />
                            <Text style={styles.loadingText}>正在加载学习计划...</Text>
                        </View>
                    ) : planBooks.length > 0 ? (
                        <FlatList
                            data={planBooks}
                            renderItem={renderBookCard}
                            keyExtractor={(item) => item.id}
                            contentContainerStyle={styles.listContainer}
                            showsVerticalScrollIndicator={false}
                        />
                    ) : (
                        <View style={styles.emptyContainer}>
                            <Image
                                source={{ uri: "https://cdn-icons-png.flaticon.com/512/4076/4076478.png" }}
                                style={styles.emptyImage}
                            />
                            <Text style={styles.emptyTitle}>还没有学习计划</Text>
                            <Text style={styles.emptyText}>选择一本教材，开始制定学习计划吧</Text>
                            <TouchableOpacity style={styles.createButton} onPress={handleAddPlan} activeOpacity={0.8}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                    style={styles.createButtonGradient}
                                >
                                    <Text style={styles.createButtonText}>去创建计划</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        </View>
                    )}
                </View>

                {/* 底部装饰 */}
                {planBooks.length > 0 && (
                    <View style={styles.footerDecoration}>
                        <Image
                            source={{ uri: "https://cdn-icons-png.flaticon.com/512/3135/3135789.png" }}
                            style={styles.footerImage}
                        />
                        <Text style={styles.footerText}>坚持学习，每天进步！</Text>
                    </View>
                )}
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    backButton: {
        width: 36,
        height: 36,
        borderRadius: 18,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.8)",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.transparent.black.light,
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.1,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    headerTitle: {
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    placeholderView: {
        width: 36,
        height: 36,
    },
    pageDescription: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: "rgba(255, 255, 255, 0.7)",
        marginHorizontal: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        padding: theme.spacing.md,
        borderRadius: theme.borderRadius.large,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.transparent.black.light,
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.1,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    descriptionIcon: {
        width: 24,
        height: 24,
        marginRight: theme.spacing.md,
    },
    descriptionText: {
        flex: 1,
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    content: {
        flex: 1,
        paddingHorizontal: theme.spacing.lg,
    },
    loadingContainer: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
    },
    loadingImage: {
        width: 80,
        height: 80,
        marginBottom: theme.spacing.lg,
        opacity: 0.7,
    },
    loadingText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
    },
    listContainer: {
        paddingBottom: theme.spacing.xxl,
    },
    bookCard: {
        width: CARD_WIDTH,
        marginBottom: theme.spacing.xl,
        borderRadius: theme.borderRadius.extraLarge,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.transparent.black.medium,
                shadowOffset: { width: 0, height: 6 },
                shadowOpacity: 0.2,
                shadowRadius: 10,
            },
            android: {
                elevation: 6,
            },
        }),
    },
    cardGradient: {
        borderRadius: theme.borderRadius.extraLarge,
        overflow: "hidden",
    },
    bookCoverContainer: {
        alignItems: "center",
        paddingVertical: theme.spacing.lg,
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    bookCover: {
        width: 140,
        height: 180,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.md,
        justifyContent: "space-between",
        position: "relative",
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.3)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 6,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    bookIconContainer: {
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: "rgba(255, 255, 255, 0.3)",
        alignItems: "center",
        justifyContent: "center",
        alignSelf: "center",
        marginBottom: theme.spacing.md,
    },
    coverTitle: {
        color: "#FFFFFF",
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        textAlign: "center",
        textShadowColor: "rgba(0, 0, 0, 0.2)",
        textShadowOffset: { width: 0, height: 1 },
        textShadowRadius: 2,
    },
    coverSubtitle: {
        color: "#FFFFFF",
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.medium,
        textAlign: "center",
        backgroundColor: "rgba(255, 255, 255, 0.3)",
        paddingHorizontal: theme.spacing.md,
        paddingVertical: 2,
        borderRadius: theme.borderRadius.medium,
        alignSelf: "center",
        marginTop: theme.spacing.xs,
    },
    decorationImage: {
        position: "absolute",
        width: 60,
        height: 60,
        opacity: 0.2,
        top: -10,
        right: -10,
    },
    bookInfo: {
        padding: theme.spacing.lg,
    },
    bookHeader: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "flex-start",
        marginBottom: theme.spacing.md,
    },
    titleContainer: {
        flex: 1,
        marginRight: theme.spacing.md,
    },
    bookTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        marginBottom: 2,
    },
    bookSubtitle: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    statusBadge: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: theme.spacing.md,
        paddingVertical: 4,
        borderRadius: theme.borderRadius.full,
        gap: 4,
        backgroundColor: theme.colors.secondary.green.default,
    },
    statusText: {
        fontSize: theme.fontSize.xs,
        fontWeight: theme.fontWeight.medium,
        color: "#FFFFFF",
    },
    progressSection: {
        backgroundColor: "rgba(245, 247, 250, 0.8)",
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.md,
        marginBottom: theme.spacing.md,
    },
    progressInfo: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginBottom: theme.spacing.md,
    },
    progressItem: {
        flex: 1,
        alignItems: "center",
    },
    progressLabel: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.gray,
        marginBottom: 2,
    },
    progressValue: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    progressDivider: {
        width: 1,
        height: "100%",
        backgroundColor: "rgba(0, 0, 0, 0.1)",
    },
    progressBarContainer: {
        width: "100%",
    },
    progressBar: {
        height: 8,
        backgroundColor: "rgba(0, 0, 0, 0.05)",
        borderRadius: 4,
        overflow: "hidden",
    },
    progressFill: {
        height: "100%",
        borderRadius: 4,
    },
    startButton: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.md,
        gap: theme.spacing.xs,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.3)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.2,
                shadowRadius: 4,
            },
            android: {
                elevation: 3,
            },
        }),
    },
    startButtonText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: "#FFFFFF",
    },
    emptyContainer: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        paddingHorizontal: theme.spacing.xxl,
    },
    emptyImage: {
        width: 120,
        height: 120,
        marginBottom: theme.spacing.lg,
    },
    emptyTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginTop: theme.spacing.md,
    },
    emptyText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        textAlign: "center",
        marginTop: theme.spacing.sm,
        marginBottom: theme.spacing.xl,
    },
    createButton: {
        width: "100%",
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    createButtonGradient: {
        paddingVertical: theme.spacing.md,
        alignItems: "center",
        justifyContent: "center",
    },
    createButtonText: {
        color: theme.colors.neutral.white,
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
    },
    footerDecoration: {
        alignItems: "center",
        marginBottom: theme.spacing.xl,
    },
    footerImage: {
        width: 40,
        height: 40,
        opacity: 0.5,
        marginBottom: theme.spacing.xs,
    },
    footerText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        fontStyle: "italic",
    },
})

